import { useRequest } from 'ahooks';
import { setStorage, getStorage } from '@/utils/storage';
import { fetchaddressOptions } from '@/pages/BasicInfo/services';

// 字典类型数组转换为对象格式
const composeDictData = (list: Array<any>) => {
  return list;
}

export default function Page() {
  // 获取系统所有地址信息
  const { data: areaData, runAsync: fetchAllAddress, loading: loading } = useRequest(async (isRefresh: boolean | undefined = false) => {
    const arr = getStorage('areaData');
    if (!isRefresh && arr?.length > 0) {
      return arr;
    }
    const res = await fetchaddressOptions();
    if (res && Array.isArray(res)) {
      const areas = composeDictData(res);
      setStorage('areaData', areas);
      return areas;
    }
    return [];
  }, {manual: true});

  // 刷新地址
  const refreshAreaData = () => {
    fetchAllAddress(true);
  }


  // 获取地址数据
  const fetchAreaData = () => {
    if (areaData?.length) {
      return ;
    }
    fetchAllAddress();
  }

 
  return {
    areaData,
    fetchAreaData,
    refreshAreaData,
    loading,
  };
};